package com.example.afinal;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MbListActivity extends ListActivity implements Runnable, AdapterView.OnItemClickListener {
//通过网上获取数据，利用json解析，以列表的形式显示数据，并将数据传给下一个页面，通过按钮跳转页面
    Handler handler;
    private ArrayList<HashMap<String, String>> listItems; // 存放文字、图片信息
    private SimpleAdapter listItemAdapter; // 适配器

    private int msgWhat = 7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getListView().setOnItemClickListener(this);
        //实现AdapterView.OnItemClickListener接口

        initListView();
        this.setListAdapter(listItemAdapter);

        Thread t = new Thread(this); // 创建新线程
        t.start(); // 开启线程

        handler = new Handler(Looper.myLooper()) {
            public void handleMessage(Message msg) {
                if (msg.what == msgWhat) {
                    List<HashMap<String, String>> retList = (List<HashMap<String, String>>) msg.obj;
                    SimpleAdapter adapter = new SimpleAdapter(MbListActivity.this, retList, // listItems数据源
                            R.layout.list_item, // ListItem的XML布局实现
                            new String[]{"ItemTitle"},
                            new int[]{R.id.itemTitle});
                    setListAdapter(adapter);
                    Log.i("handler", "reset list...");
                }
                super.handleMessage(msg);
            }
        };



    }


    //实现静态数组显示
    private void initListView() {
        listItems = new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < 10; i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("ItemTitle", "Mbti:" + i); // Mbti标题文字
            listItems.add(map);
        }
        // 生成适配器的Item和动态数组对应的元素
        listItemAdapter = new SimpleAdapter(this, listItems,
                R.layout.list_item,
                new String[] { "ItemTitle"},
                new int[] { R.id.itemTitle}
        );
    }


    @Override
    public void run() {
        Log.i("thread","run.....");
        boolean marker = false;
        List<HashMap<String, String>> rateList = new ArrayList<HashMap<String, String>>();

        try {

            Document doc = Jsoup.connect("https://www.16personalities.com/personality-types").get();
            Log.i(TAG,"title=" + doc.title());
            // 解析mbti信息
            Elements mbtis = doc.getElementsByTag("h5");
            Elements i1s = doc.getElementsByTag("h4");
            Elements i2s = doc.getElementsByClass("snippet");//通过class获取数据
            for(int i = 0; i < mbtis.size(); i += 1) {
                Element mbE = mbtis.get(i);
                Element i1E = i1s.get(i);
                Element i2E = i2s.get(i);
                String mb = mbE.text();
                String i1 = i1E.text();
                String i2 = i2E.text();

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("ItemTitle", mb);
                map.put("ItemDetail","\n"+ i1+"\n\n"+i2+"\n");

                rateList.add(map);
                Log.i(TAG, "mbti：" + mb);

            }
            marker = true;
        } catch (MalformedURLException e) {
            Log.e("www", e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("www", e.toString());
            e.printStackTrace();
        }

        Message msg = handler.obtainMessage();
        msg.what = msgWhat;
        if(marker){
            msg.arg1 = 1;
        }else{
            msg.arg1 = 0;
        }

        msg.obj = rateList;
        handler.sendMessage(msg);

        Log.i("thread","sendMessage.....");
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        //从ListView中获取选中数据
        HashMap<String,String> map = (HashMap<String, String>) getListView().getItemAtPosition(position);
        String titleStr = map.get("ItemTitle");
        String detailStr = map.get("ItemDetail");
        Log.i(TAG, "onItemClick: titleStr=" + titleStr);
        Log.i(TAG, "onItemClick: detailStr=" + detailStr);

        //打开新的页面，传入参数
        Intent rateCalc = new Intent(this,AnalyzeActivity.class);
        rateCalc.putExtra("title",titleStr);
        rateCalc.putExtra("detail",detailStr);
        startActivity(rateCalc);

    }
}
